/**
 * 
 */
package com.ly.hotel.view.fragments.vod;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.model.Episodepart;
import com.ly.hotel.model.VodVideoBean;
import com.ly.hotel.model.Vodpart;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.msgevent.GetEpisodeVideoEvent;
import com.ly.hotel.msgevent.GetVodEpisodeListEvent;
import com.ly.hotel.msgevent.UpdateEpisodeTypeListEvent;
import com.ly.hotel.msgevent.UpdateEpisodeVideoEvent;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.common.BaseActivity;
import com.ly.hotel.view.setting.SystemSettingActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * @author jouson 2015-1-10
 */
public class EpisodeActivity extends BaseActivity {

	private static final String TAG = "EpisodeActivity";
	// 电视剧类别的名字列表Adapter
	private VodEpisodeAdapter vodTypeListAdapter;

	// 搜索键盘GridLayout
	private GridLayout keyboardView;
	
	// 电视剧分类的ArrayList在这里
	private List<Episodepart> episodeList = new ArrayList<Episodepart>();

	private List<Episodepart> appEpisode;
	
	//当前选择的电视剧类型
	private int typeListIndex;

	// 电视剧图片与文字的view
	private GridView mGridView;

	// 这两个只是当前的list，会变的,每次调用updateVodItem()的时候，都要刷新一下
	private MyApplication app;

	private int tryTimes = 3;
	private ThisHandler handlerMsg = new ThisHandler(this);
	public Vodvideo video;
	
	public EditText searchEdit;
	public Button searchClaer;
	public Button searchBackspace;
	
	private ImageView epidownMore;
	private TextView totalText;
	private TextView nameText;
	private String updateName;
	
	private String keys[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T",
			"U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
	
	public static final int INIT_VIEW =  2;
	public static final int UPDATE_TYPE_LIST =  7;
			
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_episode);
		app = (MyApplication) getApplicationContext();
		findView();
		initKeyboard();
		
		// 获取电影分类列表
		handlerMsg.sendEmptyMessageDelayed(INIT_VIEW, 200);
	}
	
	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy");
	}
	
	@Override
	public void finish() {
		super.finish();
	}
	

	@Override
	public void onPause() {
		if(handlerMsg.hasMessages(UPDATE_TYPE_LIST)){
			handlerMsg.removeMessages(UPDATE_TYPE_LIST);
		}
		if(handlerMsg.hasMessages(INIT_VIEW)){
			handlerMsg.removeMessages(INIT_VIEW);
		}
		super.onPause();
	}
	
	private void initKeyboard(){
		searchClaer.setTag(getString(R.string.movie_search_clear));
		searchBackspace.setTag(getString(R.string.movie_search_backspace));
		searchClaer.setOnClickListener(btnTouchListenter);
		searchBackspace.setOnClickListener(btnTouchListenter);
		int marginInt = getResources().getDimensionPixelSize(R.dimen.px3);
		int layoutInt = getResources().getDimensionPixelSize(R.dimen.px85);
		for ( String key:keys) {
			Button tmpBtn = new Button(getBaseContext());
			tmpBtn.setTag(key);
			tmpBtn.setText(key);
			tmpBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.act_keyboard_btn));
			tmpBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.px32));
			GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
			layoutParams.width = layoutInt;
			layoutParams.height = layoutInt;
			layoutParams.setMargins(marginInt,marginInt,marginInt,marginInt);
			tmpBtn.setLayoutParams(layoutParams);			
			keyboardView.addView(tmpBtn);
			tmpBtn.setOnClickListener(btnTouchListenter);
		}
	}

	private OnClickListener btnTouchListenter = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			String key = arg0.getTag().toString();			
			if(key.equals(getString(R.string.movie_search_clear))){
				String info = searchEdit.getText().toString();
				if(!TextUtils.isEmpty(info)){
					searchEdit.setText("");
					initTypeListView();
				}
			}else if(key.equals(getString(R.string.movie_search_backspace))){
				String info = searchEdit.getText().toString();
				if(!TextUtils.isEmpty(info)){
					info = info.substring(0, info.length()-1);
					searchEdit.setText(info);
					updateName = searchEdit.getText().toString();
					if(TextUtils.isEmpty(updateName)){
						initTypeListView();
					}else{
						updateVodSearchItemList(updateName);
					}
				}
			}else {
				if(searchEdit.getText().toString().length() < 15){
					searchEdit.append(key);
					if(searchEdit.getText().toString().equals("PREGOOD")){	
						Intent intent = new Intent(EpisodeActivity.this,SystemSettingActivity.class);
						startActivity(intent);
					} else if(searchEdit.getText().toString().equals("PREVIP")){
						app.setLiuweiTime(60);
					}else {
						updateName = searchEdit.getText().toString();
						updateVodSearchItemList(updateName);
					}
				}else{
					Toast.makeText(EpisodeActivity.this, "输入限制！Restrict input！", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};
	
	private void findView() {
		keyboardView = findViewById(R.id.keyboardView);
		nameText = findViewById(R.id.vod_name);
		totalText = findViewById(R.id.vod_count);
		epidownMore = findViewById(R.id.epi_down_more);
		searchEdit = keyboardView.findViewById(R.id.search_edit);
		searchClaer = keyboardView.findViewById(R.id.search_clear);
		searchBackspace = keyboardView.findViewById(R.id.search_backspace);
		LinearLayout mvBtn = findViewById(R.id.movieButton);
        mvBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EpisodeActivity.this, VodActivity.class);
                startActivity(intent);
            }
        });
	}

	private void initTypeListView() {
		/* 初始化类型 */
		appEpisode = MyApplication.getVodEpisode();
		if (appEpisode != null && !appEpisode.isEmpty()) {
			if (appEpisode.size() > 0) {
				// 清掉再加
				episodeList.clear();
				episodeList.addAll(appEpisode);
				if(episodeList.size() >= 1){	
					updateName = getResources().getString(R.string.movie_total);
					updateTypeListView();
				}
			}
		} else {
			if(tryTimes>0){
				tryTimes--;
				EventBus.getDefault().post(new GetVodEpisodeListEvent());
				ProcessWaitingUtil.showProcessDialog(this, "获取视频列表数据中..", 3000);
			}
		}
	}
	
	//更新电视剧列表
	private void updateTypeListView(){
		if(episodeList != null){
			nameText.setText(updateName);
			totalText.setText(episodeList.size() + " " + getResources().getString(R.string.movie_videos));
		}
		if (episodeList.size() == 0 || mGridView == null) {
			return;
		}
		if(vodTypeListAdapter == null){
			vodTypeListAdapter = new VodEpisodeAdapter(this, episodeList);
			mGridView.setAdapter(vodTypeListAdapter);
		}else{
			vodTypeListAdapter.notifyDataSetChanged();
		}
	}
	
	private void setListener() {		
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
				Episodepart epp = episodeList.get(pos);
				Vodpart vpart = epp.getmovieType();
				typeListIndex = appEpisode.indexOf(epp);
				Log.i(TAG, "position=" + vpart.getVodpartname() + ":" + pos);
				// 有数据就开始活动
				if (updateVodItemList(episodeList.get(pos))) {
					startEpisodeDetailView();
				} else {// 没数据就请求
					ProcessWaitingUtil.showProcessDialog(EpisodeActivity.this, "获取剧集列表数据中..", 3000);
					EventBus.getDefault().post(new GetEpisodeVideoEvent(episodeList.get(pos)));
				}
			}
		});

		mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if((firstVisibleItem + visibleItemCount) == totalItemCount){
					epidownMore.setVisibility(View.INVISIBLE);
				}else{
					epidownMore.setVisibility(View.VISIBLE);
				}
			}
		});
	}
	
	private Boolean updateVodItemList(Episodepart epart) {
		Boolean rv = false;
		List<VodVideoBean> list;
		if(MyApplication.getVodEpisode() != null){
			/* 根据列表的类型索引获取改索引下的所有视频数据 */
			list = epart.getVodvideoBeanList();
			if (list != null) {
				rv = true;
			}
		}
		return rv;
	}
	
	//本地匹配搜索结果
	private void updateVodSearchItemList(String c) {
		List<Episodepart> appEpisode = MyApplication.getVodEpisode();
		episodeList.clear();
		List<Episodepart> slist = new ArrayList<>();
		if (appEpisode != null && !appEpisode.isEmpty()) {
			for (Episodepart ep : appEpisode) {
				String name = ep.getmovieType().getAllname();
				if (name.contains(c)) {
					slist.add(ep);
				}
			}
			if (slist.size() > 0) {
				episodeList.addAll(slist);
			}
		}
		updateTypeListView();
	}
	
	private void startEpisodeDetailView(){
		if (episodeList.size() == 0 || mGridView == null || typeListIndex < 0) {
			return;
		}
		String title = LanguageUtil.getTextFromLocalLanguage(appEpisode.get(typeListIndex).getmovieType().getVodpartname().replace("TV_", ""));
		EpisodeDetailActivity.actionStart(EpisodeActivity.this, title, typeListIndex);
	}
	
	/* 这个只是一个事件，具体的信息需要app.getVodpart()获得 */
	public void onEventMainThread(UpdateEpisodeVideoEvent e) {
		Log.i(TAG, "获取视频节目列表，typeListIndex=" + typeListIndex);
		ProcessWaitingUtil.closeProcessDialog();
		if (e.isValidUpdate()) {
			startEpisodeDetailView();
		} else {
			// 数据失败提示
			ToastUtil.showShortToast(this, "通讯故障,请稍后再试", 3000);
		}
	}

	public void onEventMainThread(UpdateEpisodeTypeListEvent e) {
		Log.i(TAG, "更新电视剧列表" + e.isValidUpdate());
		ProcessWaitingUtil.closeProcessDialog();
		if(e.isValidUpdate()){		
			handlerMsg.sendEmptyMessage(UPDATE_TYPE_LIST);
		}else{
			ToastUtil.showShortToast(this, "通讯故障,请稍后再试", 3000);
		}
	}
	/**
	 * handler处理消息机制
	 */
	private static class ThisHandler extends Handler {
		private WeakReference<EpisodeActivity> wrActivity;

		public ThisHandler(EpisodeActivity activity) {
			wrActivity = new WeakReference<EpisodeActivity>(activity);
		}

		@Override
		public void handleMessage(final Message message) {
			final EpisodeActivity act = wrActivity.get();
			Log.i(TAG, "handleMessage="+message.what);
			if (act != null) {
				switch (message.what) {
				case INIT_VIEW:
					act.mGridView = (GridView) act.findViewById(R.id.mVodGridViewA);
					act.setListener();
					act.initTypeListView();
					break;	
				case UPDATE_TYPE_LIST:
					act.initTypeListView();
					break;
				}
			}
		}
	}
}
